package com.lg.my.netty.splitpacket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("收到服务器消息:" + msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyClientHandler发送数据");
        //ctx.writeAndFlush("测试String编解码");
        //测试对象编解码
        //ctx.writeAndFlush(new User(1,"zhuge"));
        //测试用protostuff对对象编解码
        //ByteBuf buf = Unpooled.copiedBuffer(ProtostuffUtil.serializer(new User(1, "zhuge")));
        //ctx.writeAndFlush(buf);

        for (int i = 0; i < 10000; i++) {
            String msg = "你好，我是你爸爸！";
            TimeUnit.SECONDS.sleep(1);
            final MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLen(msg.getBytes(StandardCharsets.UTF_8).length);
            messageProtocol.setContent(msg.getBytes(StandardCharsets.UTF_8));

            ctx.channel().writeAndFlush(messageProtocol);
        }

    }
}
